<?php
require '../execute/auth.php';
require '../config/config.php';

mydb_connect();

if(isset($_POST['submit'])) {
	function clean($str) {
		$str = @trim ( $str );
		if (get_magic_quotes_gpc ()) {
			$str = stripslashes ( $str );
		}
		return $str;
	}
	
	$firstname = $_POST ['firstname'];
	$lastname = $_POST ['lastname'];
	$email = clean ( $_POST ['email'] );
	$password = clean ( $_POST ['password'] );
	$role='int_author';
	$twitter_id = $_POST['twitter_id'];
	
	//Check wether the user already exists in system

	$check_user = $conn->prepare("SELECT * FROM `users` WHERE email=:email");
	$check_user->execute(array('email'=> $email));
	if($check_user->rowCount()==1) 
		{
			header("Location: ../authors.php?authorExists=true");
			exit();
		}
	if (empty ( $firstname ) || empty ( $lastname ) || empty ( $email ) || empty ( $password )) {
		echo "Empty fields aren't accepted. <a href='../authors.php'><< Go back</a>";
		exit();
	} else {
		$md5password = md5 ( $password );
		
		// add to the database
		$add = $conn->prepare("INSERT INTO `users` VALUES(NULL,:firstname,:lastname,:email,:password,:role)");
		$add->execute(array('firstname'=>$firstname,'lastname'=>$lastname, 'email'=> $email, 'password'=>$md5password, 'role' => $role));
		if ($add) {
			$select_last = $conn->query("SELECT * FROM `users` ORDER BY `id` DESC LIMIT 1");
			$last_row = $select_last->fetch();
			$insert = $conn->prepare("INSERT INTO `user_authors`(`id`, `twitter_id`, `role`) VALUES(:id,:twitter_id,:role)");
			$insert->execute(array('id'=>$last_row['id'], 'twitter_id'=>$twitter_id, 'role'=>'internal'));
			if(!$insert){
				echo mysql_error();
				exit();
			}
			$message = "Welcome '$firstname', your login info is as follow: \n\n";
			$message.="Login Id: " . $email . "\n\n";
			$message.="Password: " . $password . "\n\n";
			$message.="Click the following link to access your dashboard.\n\n";
			$message.="http://tech.af/author/ \n\n";
			$message.="Thanks you.";

			$mail = mail($email, 'Tech.af Author Account Info', $message, 'From:info@tech.af');
			if($mail){
				header("Location: ../authors.php?add=success");
			}
			else{
				header("Location: ../authors.php?add=fail");
			}
		} else {
			$errmsg_arr [] = "User could not be added to the database. Reason: " . mysql_error ();
			$errflag = true;
		}
	}
} else {
	header ( "Location: ../authors.php" );
}
?>